import axios, { AxiosRequestHeaders } from 'axios'
import Taro from '@tarojs/taro'
import axiosAdapter from 'axios-miniprogram-adapter';

// 配置 axios 使用适配器
axios.defaults.adapter = axiosAdapter;

const instance = axios.create({
  baseURL: 'https://www.forbeings.com',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
  // adapter: TaroAdapter
});

// 请求拦截器
instance.interceptors.request.use(
  async (config) => {
    const token = Taro.getStorageSync('token') || '';
    // 可以在这里添加请求头，例如添加token
    // config.headers['Authorization'] = `Bearer ${token}`
    const headers = {
      ...config.headers,
      Authorization: `Bearer ${token}`
    }
    let new_config = { ...config }
    new_config.headers = headers as AxiosRequestHeaders
    console.log('new_config', new_config)
    return new_config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    // 可以在这里对响应数据进行处理
    return response.data;
  },
  error => {
    // 在这里处理全局的错误消息提示
    let errorMsg = '请求失败';
    if (error.response) {
      const { status, data } = error.response;
      switch (status) {
        case 400:
          errorMsg = data.message || '请求错误';
          break;
        case 401:
          errorMsg = '未授权，请重新登录';
          break;
        case 403:
          errorMsg = '拒绝访问';
          break;
        case 404:
          errorMsg = '请求地址出错';
          break;
        case 500:
          errorMsg = '服务器内部错误';
          break;
        default:
          errorMsg = '网络错误';
      }
    } else if (error.request) {
      errorMsg = '请求未响应';
    } else {
      errorMsg = error.message;
    }

    Taro.showToast({
      title: errorMsg,
      icon: 'none',
      duration: 2000
    });

    return Promise.reject(error);
  }
);


// 封装的get,post.put,delete请求
const get = async (url: string, parameter = {}) => {
  try {
    const res = await instance(url, {
      method: 'get',
      params: parameter,
    });
    return res;
  } catch (error) {
    console.error('get请求方式报错', error);
  }
};

const deletes = async (url: string, parameter = null) => {
  try {
    const res = await instance(url, { method: 'delete', data: parameter });
    return res;
  } catch (error) {
    console.error('deletes请求方式报错', error);
  }
};

const post = async (url: string, data = {}) => {
  try {
    const res = await instance(url, { method: 'post', data });
    return res;
  } catch (error) {
    console.error('post请求方式报错', error);
  }
};

const put = async (url: string, parameter = null) => {
  try {
    const res = await instance(url, {
      method: 'put',
      data: parameter,
    });
    return res;
  } catch (error) {
    console.error('put请求方式报错', error);
  }
};

export const request = {
  get, post, put, deletes
}

export default instance